﻿var username;
$(document).ready(function() {
	$("<div id = 'xchatbox-login'> \
			<input type = 'text' id = 'xchatbox-login-input'/> \
	   </div>").dialog({
			buttons: {
				"确定": function() {
					username = $("input#xchatbox-login-input").val();
					if(username != "") {
						window.socket.emit('login', username);
						$(this).dialog("close");
					}
					$("#ui-dialog-title-xchatbox-login").css("color", "red");
					$("input#xchatbox-login-input").focus();
				}
			},
			closeOnEscape: false,
			draggable: false,
			modal: true,
			resizable: false,
			title: "请输入您的昵称：",
			width: 244
	   });
	$("#xchatbox-form input").button();
	var flag = 0;
	$("#xchatbox").mouseenter(function() {
		if(flag == 0) {
			flag = 1;
			$("#xchatbox").animate({
				right: "-4px"
			}, function() {
				flag = 0;
			});
		}
	});
	$("#xchatbox").mouseleave(function() {
		if(flag == 0) {
			flag = 1;
			$("#xchatbox").animate({
				right: "-250px"
			}, function() {
				flag = 0;
			});
		}
	});
	$("form#xchatbox-form").submit(function (evt) {
		evt.preventDefault();
		window.socket.emit('msg', $("textarea#xchatbox-msg-input").val());
		$("textarea#xchatbox-msg-input").val("");
	});
	if (window.socket) {
		socket.on('msg', function (data) {
			window.message(data);
		});
		socket.on('sysMsg', function (data) {
			window.sysMessage(data);
		});
	}
});

window.message = function(data) {
	if(typeof(data.msg) != "undefined") {
		
		$("div#xchatbox-message").append("<div class = 'xchatbox-msg-box'>" 
										+ "<span class='xchatbox-username'>" + data.username + "</span>" 
										+ "说道：<br />" + data.msg.replace(/\n/g,"<br />") 
										+ "<span class='xchatbox-aux'>" + data.time + "</span>" 
										+ "</div>");
	}
}

window.sysMessage = function(data) {
	if(typeof(data.msg) != "undefined") {
		
		$("div#xchatbox-message").append("<div class = 'xchatbox-msg-box'>"
										+ "<span class='xchatbox-username'>" + data.username + "</span>"
										+ data.msg
										+ "<span class='xchatbox-aux'>" + data.time + "</span>"
										+ "</div>");
	}
}
